package org.example.sprojcet.job;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.sprojcet.entitys.properties.FileProperties;
import org.example.sprojcet.service.BookService;
import org.example.sprojcet.utils.FilesUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.ArrayList;
import java.util.List;

//public class ImgQuartzJob implements Job {
//    @Override
//    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//        System.out.println("单体项目 Quartz 持久化任务执行：" + System.currentTimeMillis());
//    }
//}

    //4.重新编写ImgQuartzJob定时任务方法
    @RequiredArgsConstructor
    @Slf4j
    public class ImgQuartzJob implements Job {
        private final BookService bookService;
        private final FilesUtils filesUtils;
        private final FileProperties fileProperties;
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            try {
                List<String> imagesNames = bookService.getImagesNames();
                if (imagesNames.isEmpty()) return;
                List<String> imgs = filesUtils.listFileNames(fileProperties.getImgAddress());
                if (imgs.isEmpty()) return;
                // 找出 imagesNames 中有，但 strings 中没有的
                List<String> difference = new ArrayList<>(imgs);
                difference.removeAll(imagesNames);
                for (String name : difference) {
                    filesUtils.deleteFile(fileProperties.getImgAddress()+name);
                }
            } catch (Exception e) {
                log.error(e.toString());
                throw new RuntimeException(e);
            }
        }
    }
